#include "appCommon.h"
#include "taskUSBTransfe.h"

#include "FreeRTOS.h"
#include "task.h"
#include "stream_buffer.h"

#include "usb_composite.h"
#include "usb_bulk.h"
#include "usb_hid.h"

static QueueHandle_t queueUSBData = NULL;
static __MSG_USB_RECV_DATA usbMsg;

VARIABLE_ALIGN(static uint8_t dataBuffer[512],4);

void appTask_USBTransfe(void *pvParameters)
{
    size_t xReceivedBytes;
//    BaseType_t xHigherPriorityTaskWoken ;
    
//    usb_bulk_transfer_buffer_info bufferInfo;
//    usbBulkGetBufferInfo(&bufferInfo);
//    usbBulkStartReceive();
    queueUSBData = xQueueCreate(5, sizeof(usbMsg));
    if(queueUSBData == NULL)
    {
        while(1);
    }
    while(1)
    {
//        xHigherPriorityTaskWoken = pdFALSE;

//        ulTaskNotifyTake(pdTRUE,portMAX_DELAY);
//        memcpy(bufferInfo.sendBuffer,bufferInfo.receiveBuffer,bufferInfo.sendByteSize);
//        usbBulkStartReceive();
//        usbBulkStartSend();
        
        if(xQueueReceive(queueUSBData, (void *)&usbMsg, pdMS_TO_TICKS(0xFFFFFFFF)))
        {
            if(usbMsg.dataFrom == FROM_BULK)
            {
                USB_DeviceBulkStartRecv();
            }
            else if(usbMsg.dataFrom == FROM_HID)
            {
                USB_DeviceHidStartRecv();
            }
        }
    }
}

void USB_DeviceBulkReceiveData(uint8_t *buffer,uint32_t length)
{
    __MSG_USB_RECV_DATA usbMsg;
    usbMsg.bufferAddr = buffer;
    usbMsg.length = length;
    usbMsg.dataFrom = FROM_BULK;
    
    BaseType_t xHigherPriorityTaskWoken = pdFALSE;
    xQueueSendFromISR( queueUSBData, &usbMsg, &xHigherPriorityTaskWoken );
    portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
}

void USB_DeviceHIDReceiveData(uint8_t *buffer,uint32_t length)
{
    __MSG_USB_RECV_DATA usbMsg;
    usbMsg.bufferAddr = buffer;
    usbMsg.length = length;
    usbMsg.dataFrom = FROM_HID;
    
    BaseType_t xHigherPriorityTaskWoken = pdFALSE;
    xQueueSendFromISR( queueUSBData, &usbMsg, &xHigherPriorityTaskWoken );
    portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
}
